# This file is part of Gehyra.
#
# Gehyra is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Gehyra is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gehyra.  If not, see <http://www.gnu.org/licenses/>.

"""
@package gehyra.entity.manager
Object for managing all entities associated with this node
Manages the configuration files available to the node.
$Id: manager.py 450 2011-01-20 14:28:47Z andyhhp@gmail.com $
"""

"""
@file gehyra/entity/manager.py
Object for managing all entities associated with this node
Manages the configuration files available to the node.
"""

import sys

from gehyra.common.logger import LOG
from gehyra.common.interfaces import (IEntityManager, IEntity)

from zope.interface import implements
from zope.interface.verify import verifyObject

class Manager(object):
    """Entity Manager singleton class.
    Controls all entites for the node.
    """
    implements(IEntityManager)

    def __init__(self, main):
        """Constructor.
        @param main Main gehyra object
        """
        ## Reference to main gehyra object
        self.main = main

        ## @brief List of entities
        self.entities = []

    def initialize(self):
        """Initialize.
        Read the entity configuration and populate the entity list
        """
        cfg = self.main.config_manager
        
        for name in cfg.node['entities']['list']:

            try:
                t = cfg.node['entities'][name+".type"]
                a = cfg.node['entities'][name+".args"]
            except KeyError:
                LOG.warn("Entity object '%s' must have a type and arguments"
                         % name)
                continue

            LOG.debug("Found entity option: %s of type %s" % (name, t) )

            # This is where the magic happens:
            # dynamically import the specified module
            mod_name = 'gehyra.entity.modules.'+t
            try:
                __import__(mod_name, globals(), locals(), [], -1)
            except ImportError as e:
                LOG.warn("Unable to import '%s' as an entity: %s"
                         % (mod_name, e))
                continue

            # create an instance of that object with the specified parameters
            mod_object = sys.modules[mod_name].__dict__[t](self.main,
                                                           self, name, **a)
            verifyObject(IEntity, mod_object)

            # append to bootstrap list
            self.entities.append(mod_object)

        if len(self.entities) < 1:
            LOG.warn("No valid entities found")

        for e in self.entities:
            e.initialize()
        
        return True
